Grokking Microsoft Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Microsoft Easy Problems
Buddy Strings (easy)
Solution: Buddy Strings
Can Place Flowers (easy)
Solution: Can Place Flowers
Reverse a LinkedList (easy)
Solution: Reverse a LinkedList
Maximum Number of Balloons (easy)
Solution: Maximum Number of Balloons
Binary Tree Path Sum (easy)
Solution: Binary Tree Path Sum
Pair with Target Sum (easy)
Solution: Pair with Target Sum
Buy Two Chocolates (easy)
Solution: Buy Two Chocolates
Root Equals Sum of Children (easy)
Solution: Root Equals Sum of Children
Excel Sheet Column Title (easy)
Solution: Excel Sheet Column Title
Merge Strings Alternately (easy)
Solution: Merge Strings Alternately
Min Cost Climbing Stairs (easy)
Solution: Min Cost Climbing Stairs
Plus One (easy)
Solution: Plus One
Intersection of Two Arrays (easy)
Solution: Intersection of Two Arrays
Find the Index of the First Occurrence in a String (easy)
Solution: Find the Index of the First Occurrence in a String
Merge Two Sorted Lists (easy)
Solution: Merge Two Sorted Lists
Microsoft Medium Problems
Nth Digit (medium)
Solution: Nth Digit
Restore IP Addresses (medium)
Solution: Restore IP Addresses
Find Original Array From Doubled Array (medium)
Solution: Find Original Array From Doubled Array
Reverse Words in a String II (medium)
Solution: Reverse Words in a String II
Longest Arithmetic Subsequence (medium)
Solution: Longest Arithmetic Subsequence
Matchsticks to Square (medium)
Solution: Matchsticks to Square
Score of Parentheses (medium)
Solution: Score of Parentheses
Maximum Length of a Concatenated String with Unique Characters (medium)
Solution: Maximum Length of a Concatenated String with Unique Characters
Inorder Successor in BST (medium)
Solution: Inorder Successor in BST
Distribute Coins in Binary Tree (medium)
Solution: Distribute Coins in Binary Tree
Spiral Matrix (medium)
Solution: Spiral Matrix
Delete Node in a BST (medium)
Solution: Delete Node in a BST
Sum of Subarray Minimums (medium)
Solution: Sum of Subarray Minimums
Rotate Image (medium)
Solution: Rotate Image
Combinations (medium)
Solution: Combinations
Maximum Level Sum of a Binary Tree (medium)
Solution: Maximum Level Sum of a Binary Tree
Multiply Strings (medium)
Solution: Multiply Strings
Best Time to Buy and Sell Stock II (medium)
Solution: Best Time to Buy and Sell Stock II
Largest Palindromic Number (medium)
Solution: Largest Palindromic Number
Remove Duplicate Letters (medium)
Solution: Remove Duplicate Letters
Next Permutation (medium)
Solution: Next Permutation
132 Pattern (medium)
Solution: 132 Pattern
Valid Sudoku (medium)
Solution: Valid Sudoku
Number of Islands (medium)
Solution: Number of Islands
Buildings With an Ocean View (medium)
Solution: Buildings With an Ocean View
Regular Expression Matching (hard)
Solution: Regular Expression Matching
First Missing Positive (hard)
Solution: First Missing Positive
Largest Rectangle in Histogram (hard)
Solution: Largest Rectangle in Histogram
Sliding Window Maximum (hard)
Solution: Sliding Window Maximum
Count Unique Characters of All Substrings of a Given String (hard)
Solution: Count Unique Characters of All Substrings of a Given String
Word Ladder (hard)
Solution: Word Ladder
Word Ladder II (hard)
Solution: Word Ladder II
Number of Flowers in Full Bloom (hard)
Solution: Number of Flowers in Full Bloom
Median of Two Sorted Arrays (hard)
Solution: Median of Two Sorted Arrays
Longest Valid Parentheses (hard)
Solution: Longest Valid Parentheses
Solution: Delete Node in a BST

Problem Statement

Given a root node of the binary search tree, and an integer value key, return the root of the updated BST after deleting the node having a value equal to key.

If BST doesn't contain the node having value equal to key, return the same binary tree.

Examples

Example 1:

  • Input: [8, 3, 10, 1, 6, null, 14, null, null, 4, 7, 13], key = 3
Image
  • Expected Output: [8, 4, 10, 1, 6, null, 14, null, null, null, 7, 13]
  • Justification: After removing the node with value 3, its right subtree's smallest value (4) replaces it to maintain the BST structure.

Example 2:

  • Input: [20, 10, 30, null, 15, 25, 35], key = 10
Image
  • Expected Output: [20, 15, 30, null, null, 25, 35]
  • Justification: The node 10 is removed and replaced by its right child 15 to keep the tree's integrity.

Example 3:

  • Input: [50, 30, 70, 20, 40, 60, 80], key = 10
Image
  • Expected Output: [50, 30, 70, 20, 40, 60, 80]
  • Justification: The BST doesn't contain the node with value 10. So, it returns the original BST.

Solution

To solve this problem, we will traverse the BST to find the target node to be deleted. If the target node has both left and right children, we'll find its in-order successor (the smallest node in its right subtree) to replace it, ensuring the BST's properties remain intact. If the target node has only one child or no children, we'll simply remove the node and connect its parent to its child if it exists.

This approach works because it respects the BST properties by carefully choosing a replacement for the deleted node when necessary and properly handling leaf nodes and nodes with a single child. It's effective because it minimally disrupts the tree's structure, requiring no unnecessary movements or changes beyond those needed to preserve the BST properties.

Step-by-step Algorithm

  1. Check if the root is null: If the root is null, there is no tree to modify, so return null.
  2. Search for the node to delete: Traverse the tree to find the node with the value equal to the key. Keep track of the parent node as you search, as you'll need it to update the tree structure after deletion.
  3. Node not found: If the node is not found (i.e., we reach a null pointer), return the root as is because there's nothing to delete.
  4. Handle node with two children:
    • If the node to be deleted has both left and right children, find the in-order successor of the node, which is the smallest node in its right subtree.
    • Swap the value of the node to be deleted with the in-order successor's value. This effectively moves the problem of deletion to a node with fewer than two children.
    • Update the current node to the in-order successor and the parent to the in-order successor's parent for the next steps.
  5. Handle node with one or no child:
    • Determine the single child of the node (if it exists) by checking if the left child is not null. Otherwise, use the right child (which could also be null if the node has no children).
    • If the node to be deleted is the root (i.e., parent is null), then the root should be updated to this single child.
    • If the node to be deleted is not the root, update the parent's link to bypass the node to be deleted, effectively removing it from the tree. This involves setting the appropriate child pointer (left or right) of the parent to the single child of the node to be deleted.
  6. Return the possibly updated root of the tree, as the deletion of a node might have changed the tree's root (especially in cases where the root itself is deleted and has a single child or no child).

Algorithm Walkthrough

Let's consider the input:

        8
       / \
      3   10
     / \    \
    1   6    14
       / \  /
      4   7 13
  • Key to Delete: 3

Steps:

  1. Start with the root: root = 8. The root is not null, so we proceed to find the node with the key to delete.
  2. Search for the node with value 3:
    • Start from the root. Current node (cur) is 8, and its value does not match the key. Parent (parent) is initially null.
    • Move to the left child of 8 since 3 is less than 8. Now, cur = 3 and parent = 8.
    • The value of cur matches the key. Node to delete is found.
  3. Check children of node 3:
    • Node 3 has two children (1 and 6), so we need to find the in-order successor in its right subtree.
  4. Find in-order successor of node 3:
    • The in-order successor is the smallest node in the right subtree of 3. We start at node 6.
    • Move to the left child of 6 to find the smallest node, which is 4. No further left children, so succ = 4 and succParent = 6.
  5. Replace node 3 with its in-order successor 4:
    • Swap values: Now, instead of deleting 3, we delete 4 after copying its value to 3. So, the value of cur (which is 3) becomes 4.
    • Adjust pointers to delete 4. Since 4 has no left child, we directly proceed to its deletion.
  6. Handle deletion of 4 (which now effectively takes the place of 3 for deletion due to value swap):
    • Node 4 is a leaf (no children), so we simply remove it by updating its parent's link.
    • 4 is the left child of 6. So, we set the left child of succParent (6) to null.
  7. Final Tree Structure:
        8
       / \
      4   10
     / \    \
    1   6    14
         \  /
          7 13

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

The time complexity of the algorithm is , where h is the height of the binary search tree (BST). In the worst-case scenario, the node to be deleted is located at the bottom of the tree, requiring a traversal from the root to a leaf node.

Space Complexity

The space complexity of the algorithm is for the system's call stack due to recursion during the search for the node to be deleted, as well as finding the in-order successor if necessary.

Delete Node in a BST (medium)
Sum of Subarray Minimums (medium)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis